import {
  _decorator,
  Component,
  Label,
  Asset,
  ProgressBar,
  Node,
  director,
  game
} from "cc";
import CCCHotfix, { HotfixUpdateState, UpdateState } from "./components/hot_updata";

const { ccclass, property } = _decorator;

@ccclass("hotup3_6after")
export class hotup3_6after extends Component {

  @property(Label)
  logLabel: Label = null!;

  @property(Label)
  versionLabel: Label = null!;

  @property(ProgressBar)
  progressBar: ProgressBar = null!;

  @property(Node)
  panel: Node = null!;
  

  hot_updata: CCCHotfix = null!;

  onLoad(): void {
    this.hot_updata = CCCHotfix.me;
    this.hot_updata.init();

    // 注册事件
    this.hot_updata.e.on(CCCHotfix.Event.ResVersionUpdate, this._onResVersionUpdate, this);
    this.hot_updata.e.on(CCCHotfix.Event.Tip, this._onTip, this);
  }


  onDestroy(): void {
    this.hot_updata.e.off(CCCHotfix.Event.ResVersionUpdate, this._onResVersionUpdate, this);
    this.hot_updata.e.off(CCCHotfix.Event.Tip, this._onTip, this);
  }

  private _onResVersionUpdate(version: string) {
    this.versionLabel.string = version;
  }

  private _onTip(tip: string) {
    this.logLabel.string = tip;
  }

  start() {
    this.hot_updata.checkUpdate().then((need) => {
      console.log("checkUpdate", need);
      if (need.needUpdate) {
        this.hot_updata.doUpdate(this.listener);
      } else {
        director.loadScene("scenes/game");
      }
    });
  }

  listener(state: HotfixUpdateState, progress?: number) {
    if (state === UpdateState.Success) {
      this._onTip("✅️ Hot update success.");
      // 重启游戏
      game.restart();
      director.reset();

    } else if (state === UpdateState.Fail) {
      this._onTip("‼️ Hot update fail.");
    } else if (state === UpdateState.Progress) {
      // this._onTip("🔄️ Hot update progress: " + progress + "%");
      // this.progressBar.node.active = true;
      console.log("progress: ", progress);
      this.progressBar.progress = progress / 100;
    }
  }

  update(deltaTime: number) {}
}
